package com.nexgo.payment.trans.cardhint;

import android.os.SystemClock;
import android.support.annotation.NonNull;

import com.nexgo.oaf.apiv3.device.beeper.Beeper;
import com.nexgo.oaf.apiv3.device.reader.CardReader;
import com.nexgo.oaf.apiv3.device.reader.CardSlotTypeEnum;
import com.nexgo.payment.aop.annotation.RunOnMainThread;
import com.nexgo.payment.aop.annotation.RunOnWorkThread;
import com.nexgo.payment.api.ApiDeviceEngine;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.sound.SoundManager;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 拔卡操作类
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年8月31日
 */
public class CardHintPresenter implements CardHintContract.Presenter {

    private final CardHintContract.View mView;
    private final DataSource mRepository;
    private final SoundManager mSoundManager;
    private CardReader mCardReader;
    private Beeper mBeeper;
    private boolean isFirstTimes = true;

    public CardHintPresenter(@NonNull CardHintContract.View view, @NonNull DataSource repository) {
        mView = checkNotNull(view);
        mRepository = checkNotNull(repository);
        mView.setPresenter(this);
        mCardReader = ApiDeviceEngine.getInstance().getCardReader();
        mBeeper = ApiDeviceEngine.getInstance().getBeeper();
        mSoundManager = new SoundManager();
    }

    @Override
    public void start() {
        if (isFirstTimes) {
            mSoundManager.play(SoundManager.Type.BRING_CARD);
            showCardHint();
            isFirstTimes = false;
        }
    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        mSoundManager.stop();
    }

    @Override
    @RunOnWorkThread
    public void showCardHint() {
        while (mCardReader.isCardExist(CardSlotTypeEnum.ICC1)
                || mCardReader.isCardExist(CardSlotTypeEnum.RF)) {
            mBeeper.beep(50);
            SystemClock.sleep(100);
        }
        postMainThread(() -> mView.showSuccess());
    }

    /**
     * 主线程操作
     *
     * @param runnable
     */
    @RunOnMainThread
    private void postMainThread(Runnable runnable) {
        runnable.run();
    }
}
